package com.ridu.project.beshid.service.impl;

import com.ridu.project.beshid.api.*;
import com.ridu.project.beshid.config.Global;
import com.ridu.project.beshid.config.GlobalConfiguration;
import com.ridu.project.beshid.entity.AppealEntity;
import com.ridu.project.beshid.entity.UserEntity;
import com.ridu.project.beshid.repository.AppealRepository;
import com.ridu.project.beshid.service.AppealService;
import com.ridu.project.beshid.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * Created by user on 2017/10/18.
 */
@Service
@Slf4j
public class AppealServiceImpl implements AppealService {

    @Autowired
    private GlobalConfiguration globalConfiguration;
    @Autowired
    private AppealRepository repository;

    @Override
    public GeneralResponse<Appeal> findAll(int currentPage, int pageSize) {
        GeneralResponse<Appeal> response = new GeneralResponse<>();
        try {
            if (currentPage == 0) {
                currentPage = 1;
            }
            if (pageSize == 0) {
                pageSize = Global.DEFAULT_PAGE_SIZE;
            }
            Sort sort = new Sort(Sort.Direction.DESC, "id");
            Pageable pageable = new PageRequest(currentPage - 1, pageSize, sort);
            Page<AppealEntity> page = repository.findAll(new Specification<AppealEntity>() {
                @Override
                public Predicate toPredicate(Root<AppealEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    List<Predicate> queryPredicates = new ArrayList<>();
                    queryPredicates.add(cb.or(cb.isNull(root.<String>get("status")), cb.equal(root.<String>get("status"), "")));
                    query.where(queryPredicates.toArray(new Predicate[0]));
                    return null;
                }
            }, pageable);
            List<AppealEntity> dataList = page.getContent();
            List<Appeal> list = new ArrayList<>();
            if(CollectionUtils.size(dataList) > 0){
                dataList.stream().forEach(appealEntity -> {
                    Appeal appeal = new Appeal();
                    BeanUtils.copyProperties(appealEntity, appeal);
                    if(appealEntity.getUser() != null){
                        appeal.setUsername(appealEntity.getUser().getUsername());
                    }
                    list.add(appeal);
                });
            }
            response.setStatus(Status.SUCCESS);
            response.setRows(list);
            response.setTotal(page.getTotalElements());
        } catch (Exception e) {
            response.setStatus(Status.FAILED);
            response.setMessage(e.getMessage());
            log.error("error", e);
        }
        return response;
    }

    @Override
    public GeneralResponse audit(Long id, String status) {
        GeneralResponse response = new GeneralResponse();
        try{
            AppealEntity entity = repository.findById(id).get();
            if(entity == null){
                throw new Exception("未找到实体类！");
            }
            if(StringUtil.format(status).equals("OK")){
                entity.setStatus(Status.SUCCESS.value());
            } else if(StringUtil.format(status).equals("NO")){
                entity.setStatus(Status.FAILED.value());
            }
            repository.saveAndFlush(entity);
            response.setStatus(Status.SUCCESS);
        } catch (Exception e){
            response.setStatus(Status.FAILED);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    @Override
    public GeneralResponse save(String type, String description, UserEntity user) {
        GeneralResponse response = new GeneralResponse();
        try{
            AppealEntity entity = new AppealEntity();
            if(StringUtil.format(type).equals("excep")){
                entity.setType(AppealStatus.异常问题.value());
            } else if(StringUtil.format(type).equals("feedback")){
                entity.setType(AppealStatus.建议反馈.value());
            }
            entity.setDescription(description);
            entity.setUser(user);
            repository.save(entity);
            response.setStatus(Status.SUCCESS);
        } catch (Exception e){
            response.setStatus(Status.FAILED);
            response.setMessage(e.getMessage());
        }
        return response;
    }


}
